package cn.tedu.ivos.dictoption.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.ivos.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;
    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项业务，dictOptionQuery={}",dictOptionQuery);
        List<DictOptionVO> list = dictOptionMapper.selectDictOption(dictOptionQuery);
        return list;
    }

    @Override
    public void saveDictOption(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存字典项业务，dictOptionSaveParam={}",dictOptionSaveParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if(dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        }else{
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典编码查询字典项业务，code={}",code);
        //先查询该字典是否存在，若存在，再查询该字典code下对应的字典项
        DictQuery dictQuery = new DictQuery();//封装字典的查询对象
        dictQuery.setCode(code);//给字典查询对象设置字典编码
        List<DictVO> dictVOList = dictMapper.selectDictByCode(dictQuery);//查字典
        if(dictVOList!=null && dictVOList.size()>0){//如果根据code查到了字典
            DictVO dictVO = dictVOList.get(0);//获取当前字典对象
            DictOptionQuery dictOptionQuery = new DictOptionQuery();//封装字典项查询对象
            dictOptionQuery.setDictId(dictVO.getId());//给字典项查询对象设置字典id
            //根据字典项id查询该字典下对应的所有字典项,并返回
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);
            return dictOptionVOList;
        }else{
            //如果根据字典编码code查不到字典,就抛出“数据不存在”的业务层异常
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项业务：id={}",id);
        dictOptionMapper.deleteById(id);
    }
}






